package com.example.icongyou.service;


import com.example.icongyou.api.AssignmentApi;
import com.example.icongyou.bean.Assignment;
import com.example.icongyou.retrofit.RetrofitClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.List;

public class AssignmentService {
    private AssignmentApi api;

    public AssignmentService() {
        api = RetrofitClient.getClient().create(AssignmentApi.class);
    }

    // 创建作业
    public void createAssignment(Assignment assignment, ApiCallback<Assignment> callback) {
        api.createAssignment(assignment).enqueue(createCallback(callback));
    }

    // 根据ID获取作业
    public void getAssignment(Long id, ApiCallback<Assignment> callback) {
        api.getAssignment(id).enqueue(createCallback(callback));
    }

    // 根据课程ID获取作业列表
    public void getAssignmentsByCourse(Long courseId, ApiCallback<List<Assignment>> callback) {
        api.getAssignmentsByCourse(courseId).enqueue(createCallback(callback));
    }

    // 获取所有作业
    public void getAllAssignments(ApiCallback<List<Assignment>> callback) {
        api.getAllAssignments().enqueue(createCallback(callback));
    }

    // 更新作业
    public void updateAssignment(Long id, Assignment assignment, ApiCallback<Assignment> callback) {
        api.updateAssignment(id, assignment).enqueue(createCallback(callback));
    }

    // 删除作业
    public void deleteAssignment(Long id, ApiCallback<Void> callback) {
        api.deleteAssignment(id).enqueue(createCallback(callback));
    }

    // 根据课程ID删除作业
    public void deleteAssignmentsByCourse(Long courseId, ApiCallback<Void> callback) {
        api.deleteAssignmentsByCourse(courseId).enqueue(createCallback(callback));
    }

    // 获取活跃作业
    public void getActiveAssignments(ApiCallback<List<Assignment>> callback) {
        api.getActiveAssignments().enqueue(createCallback(callback));
    }

    // 统计课程作业数量
    public void countAssignmentsByCourse(Long courseId, ApiCallback<Integer> callback) {
        api.countAssignmentsByCourse(courseId).enqueue(createCallback(callback));
    }

    // 通用的回调处理
    private <T> Callback<T> createCallback(ApiCallback<T> callback) {
        return new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                if (response.isSuccessful() && response.body() != null) {
                    callback.onSuccess(response.body());
                } else {
                    callback.onError("请求失败: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                callback.onError("网络错误: " + t.getMessage());
            }
        };
    }

    // 回调接口
    public interface ApiCallback<T> {
        void onSuccess(T result);
        void onError(String error);
    }
}
